package net.htjs.juc.supersedeprint;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class ReentrantLockPrint {

    public static void main(String[] args) {
        AwaitSingal awaitSingal = new AwaitSingal(5);
        Condition a = awaitSingal.newCondition();
        Condition b = awaitSingal.newCondition();
        Condition c = awaitSingal.newCondition();
        new Thread(() -> {
            awaitSingal.print("a", a, b);
        }, "t1").start();
        new Thread(() -> {
            awaitSingal.print("b", b, c);
        }, "t2").start();
        new Thread(() -> {
            awaitSingal.print("c", c, a);
        }, "t3").start();
        log.info("开始执行");
        try{
            awaitSingal.lock();
            a.signal();
        } finally {
            awaitSingal.unlock();
        }
    }

    static class  AwaitSingal extends ReentrantLock {
        private int loopNumber;

        public AwaitSingal(int loopNumber) {
            this.loopNumber = loopNumber;
        }
        public void print(String str, Condition current, Condition nextCondition) {
            for(int i = 0; i < loopNumber; i++) {
                try{
                    lock();
                    current.await();
                    log.info(str);
                    nextCondition.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock();
                }
            }
        }
    }
}
